package top.kikt.book.core.handlers.common

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import top.kikt.book.core.base.IBookHandler
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.util.getUrl

interface CommonMenuHandler : IBookHandler {

    interface NodeFilter {
        fun filter(index: Int, element: Element): Boolean
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val nodes = document.select("#list > dl > dd > a")

        val filter = createNodeFilter(document, nodes)

        val filteredList = nodes.toList().filterIndexed { index, element ->
            filter.filter(index, element)
        }

        return filteredList.mapIndexed { index, it ->
            val href = it.attr("href")
            val url = menuUrl.toHttpUrl().resolve(href)
            val name = it.text().trim()
            ChapterMetaEntity(name, index, url.toString(), it)
        }
    }

    fun createNodeFilter(document: Document, nodes: Elements): NodeFilter {
        return object : NodeFilter {
            override fun filter(index: Int, element: Element): Boolean {
                return true
            }
        }
    }

    companion object Handler {
        fun convertToMetaList(container: Element, menuUrl: String): List<ChapterMetaEntity> {
            return container.getElementsByTag("a").mapIndexed { index, element ->
                val url = element.getUrl(menuUrl)
                val name = element.text()
                ChapterMetaEntity(name, index, url, element)
            }
        }
    }
}
